package game.leon.engine.letter;

import game.leon.engine.pattern.Filter;
import game.leon.engine.utils.LinkedNode;
import game.leon.engine.utils.Reciever;

/**
 * 邮局, 用来发信, 有空就发信. 把信发出去处理掉. 最后还是必须放到消息处理线程去做
 * User: bianpeng
 * Date: 12-2-8
 */
public class PostOffice<T extends Letter> {
    private Reciever<T> reciever = new Reciever<T>();
    private long firstExpireTime = 0;
    // 时间过期处理器
    private class ExpiredFilter<U extends Letter> implements Filter<U> {
        private long now;
        public ExpiredFilter(long now) {
            this.now = now;
        }
        @Override
        public boolean test(U letter) {
            long expiredTime = letter.getExpiredTime();
            if (now < expiredTime) {
                if (expiredTime < firstExpireTime) {
                    firstExpireTime = expiredTime;
                }
                return false;
            } else {
                return true;
            }
        }
    }
    public void post(T letter) {
        if (letter.getExpiredTime() < firstExpireTime) {
            firstExpireTime = letter.getExpiredTime();
        }
        reciever.recieve(letter);
    }
    public LinkedNode<T> expire() {
        long now = System.currentTimeMillis();
        if (now < firstExpireTime) return null;

        firstExpireTime = now + 10000;   // 10秒判断, 应该足够了, 也就是说, 如果真的不行, 10秒后进来判断
        ExpiredFilter<T> filter = new ExpiredFilter<T>(now);
        LinkedNode<T> expired = reciever.consume(filter);
        return expired;
    }
}
